package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.dto.CreateSubThemeRequest;
import com.example.teaching_server.dto.ThemeDTO;
import com.example.teaching_server.service.ThemeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/themes")
@RequiredArgsConstructor
@Tag(name = "主题管理", description = "主题信息查询和管理接口")
public class ThemeController {
    private final ThemeService themeService;

    /**
     * 获取所有主题
     */
    @GetMapping
    @Operation(summary = "获取主题列表", description = "获取所有主题（每个父主题只返回前3个子主题）")
    public ApiResponse<List<ThemeDTO>> getThemes() {
        log.info("开始获取主题列表");

        try {
            List<ThemeDTO> themes = themeService.getThemes();
            log.info("成功获取{}个主题", themes.size());
            return ApiResponse.success("获取主题成功", themes);
        } catch (Exception e) {
            log.error("获取主题失败", e);
            return ApiResponse.fail("获取主题失败: " + e.getMessage());
        }
    }

    /**
     * 根据父主题ID获取主题详情
     */
    @GetMapping("/details")
    @Operation(summary = "获取主题详情", description = "根据父主题ID获取该父主题和所有子主题")
    public ApiResponse<ThemeDTO> getThemeWithAllSubThemes(
            @Parameter(description = "父主题ID")
            @RequestParam Long parentId) {

        log.info("开始获取主题详情: parentId={}", parentId);

        try {
            ThemeDTO theme = themeService.getThemeWithAllSubThemes(parentId);
            log.info("成功获取主题{}的详细信息，包含{}个子主题", parentId, theme.getSubThemes().size());
            return ApiResponse.success("获取主题详情成功", theme);
        } catch (Exception e) {
            log.error("获取主题详情失败: parentId={}", parentId, e);
            return ApiResponse.fail("获取主题详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个主题详情
     */
    @GetMapping("/{themeId}")
    @Operation(summary = "获取单个主题详情", description = "根据主题ID获取主题详细信息")
    public ApiResponse<ThemeDTO> getThemeById(
            @Parameter(description = "主题ID")
            @PathVariable Long themeId) {

        log.info("开始获取单个主题详情: themeId={}", themeId);

        try {
            ThemeDTO theme = themeService.getThemeWithAllSubThemes(themeId);
            log.info("成功获取主题{}的详细信息", themeId);
            return ApiResponse.success("获取主题详情成功", theme);
        } catch (Exception e) {
            log.error("获取主题详情失败: themeId={}", themeId, e);
            return ApiResponse.fail("获取主题详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建子主题
     */
    @PostMapping("/sub-themes")
    @Operation(summary = "创建子主题", description = "创建新的子主题")
    public ApiResponse<ThemeDTO.SubThemeDTO> createSubTheme(@RequestBody CreateSubThemeRequest request) {
        log.info("开始创建子主题: parentId={}, name={}", request.getParentId(), request.getName());

        try {
            ThemeDTO.SubThemeDTO createdSubTheme = themeService.createSubTheme(request);
            log.info("子主题创建成功: subThemeId={}", createdSubTheme.getId());
            return ApiResponse.success("子主题创建成功", createdSubTheme);
        } catch (Exception e) {
            log.error("创建子主题失败", e);
            return ApiResponse.fail("创建子主题失败: " + e.getMessage());
        }
    }

    /**
     * 搜索主题
     */
    @GetMapping("/search")
    @Operation(summary = "搜索主题", description = "根据关键字搜索主题信息")
    public ApiResponse<List<ThemeDTO>> searchThemes(
            @Parameter(description = "搜索关键字")
            @RequestParam(required = false) String keyword,
            @Parameter(description = "是否包含子主题搜索")
            @RequestParam(required = false) Boolean includeSubThemes) {

        log.info("开始搜索主题: keyword={}, includeSubThemes={}", keyword, includeSubThemes);

        try {
            List<ThemeDTO> themes = themeService.getThemes();

            // 关键字筛选
            if (keyword != null && !keyword.trim().isEmpty()) {
                themes = themes.stream()
                        .filter(theme ->
                                theme.getName().toLowerCase().contains(keyword.toLowerCase()) ||
                                        theme.getLabel().toLowerCase().contains(keyword.toLowerCase()) ||
                                        (theme.getDescription() != null &&
                                                theme.getDescription().toLowerCase().contains(keyword.toLowerCase())))
                        .collect(Collectors.toList());
            }

            // 如果需要包含子主题的详细搜索
            if (includeSubThemes != null && includeSubThemes) {
                themes = themes.stream()
                        .map(theme -> {
                            try {
                                return themeService.getThemeWithAllSubThemes(theme.getId());
                            } catch (Exception e) {
                                return theme;
                            }
                        })
                        .filter(theme ->
                                theme.getSubThemes().stream()
                                        .anyMatch(subTheme ->
                                                subTheme.getName().toLowerCase().contains(keyword.toLowerCase()) ||
                                                        subTheme.getLabel().toLowerCase().contains(keyword.toLowerCase())))
                        .collect(Collectors.toList());
            }

            log.info("成功搜索到{}个主题", themes.size());
            return ApiResponse.success("主题搜索成功", themes);
        } catch (Exception e) {
            log.error("搜索主题失败", e);
            return ApiResponse.fail("搜索主题失败: " + e.getMessage());
        }
    }
}
